package com.song.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.entity.UserAccount;
import com.song.entity.UserInfo;
import com.song.entity.UserLoginRecord;
import com.song.entity.vo.*;
import com.song.exception.BusinessException;
import com.song.mapper.UserAccountMapper;
import com.song.mapper.UserInfoMapper;
import com.song.mapper.UserLoginRecordMapper;
import com.song.result.ResponseEnum;
import com.song.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.util.JwtUtils;
import com.song.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author Song
 * @since 2025-01-03
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserLoginRecordMapper userLoginRecordMapper;



    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(RegisterVO registerVO) {
        //判断用户是否已经注册过了
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("mobile",registerVO.getMobile());
        Integer count = baseMapper.selectCount(userInfoQueryWrapper);
        //判断count 自己写

        //用户信息增加
        UserInfo u = new UserInfo();
        u.setUserType(registerVO.getUserType());
        u.setNickName(registerVO.getMobile());
        u.setName(registerVO.getMobile());
        u.setMobile(registerVO.getMobile());
        u.setPassword(MD5.encrypt(registerVO.getPassword()));//待会加个密
        u.setStatus(UserInfo.STATUS_NORMAL);//状态
        u.setHeadImg("https://sj20250109.oss-cn-beijing.aliyuncs.com/images/2025/01/14/8d85cd48-4b08-4ee8-95b8-204d2e41425a.jpg");
        baseMapper.insert(u);




        //创建会员账户信息
        UserAccount ua = new UserAccount();
        ua.setUserId(u.getId());
        userAccountMapper.insert(ua);




    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserInfoVO login(LoginVO loginVO, String ip) throws BusinessException {
        String mobile = loginVO.getMobile();
        String password = loginVO.getPassword();
        Integer userType = loginVO.getUserType();
        //进行判断
        if (org.springframework.util.StringUtils.isEmpty(mobile) || org.springframework.util.StringUtils.isEmpty(password) || org.springframework.util.StringUtils.isEmpty(userType)){
            throw new BusinessException("格式错误");
        }

        //获取会员信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        wrapper.eq("user_type",userType);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        //判断用户信息是否为空----是？不能登录；否？登录。
        if (userInfo == null){
            throw new BusinessException(ResponseEnum.ERROR,"请先注册");
        }
        //到这里说明用户信息不为空---进行密码校验
        //将输入的密码进行加密

        String encrypt = MD5.encrypt(loginVO.getPassword());
        if (!userInfo.getPassword().equals(encrypt)){
            throw new BusinessException(ResponseEnum.ERROR,"密码输入错误");
        }

        //记录登录日志
        UserLoginRecord ulr = new UserLoginRecord();
        ulr.setUserId(userInfo.getId());
        ulr.setIp(ip);
        //添加到数据库中 才叫记录
        userLoginRecordMapper.insert(ulr);

        //生成token
        String token = JwtUtils.createToken(userInfo.getId(), userInfo.getName());

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setToken(token);
        userInfoVO.setName(userInfo.getName());
        userInfoVO.setNickName(userInfo.getNickName());
        userInfoVO.setHeadImg(userInfo.getHeadImg());
        userInfoVO.setMobile(userInfo.getMobile());
        userInfoVO.setUserType(userInfo.getUserType());
        return userInfoVO;
    }

    @Override
    public UserIndexVO getUserIndexVoByUserId(Long userId) {

        UserIndexVO userIndexVO = new UserIndexVO();


        //分页  倒序  拿第一条
        QueryWrapper<UserLoginRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).orderByDesc("id").last("limit 1");

        UserLoginRecord userLoginRecord = userLoginRecordMapper.selectOne(wrapper);


        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("id",userId);

        UserInfo userInfo = baseMapper.selectOne(userInfoQueryWrapper);

        //最后登录时间就有了
        userIndexVO.setLastLoginTime(userLoginRecord.getUpdateTime());
        userIndexVO.setName(userInfo.getName());
        userIndexVO.setHeadImg(userInfo.getHeadImg());
        userIndexVO.setBindStatus(userInfo.getBindStatus());
        userIndexVO.setUserType(userInfo.getUserType());

        //查询用户账户余额和冻结金额
        UserAccount userAccount = userAccountMapper.selectById(userId);//获取用户账户信息
        userIndexVO.setAmount(userAccount.getAmount());
        userIndexVO.setFreezeAmount(userAccount.getFreezeAmount());

        return userIndexVO;
    }

    @Override
    public IPage<UserInfo> listPage(Page<UserInfo> pages, UserInfoQuery userInfoQuery) {


        //对象是否为空 不为空才获取
        String mobile = userInfoQuery.getMobile();
        Integer userType = userInfoQuery.getUserType();
        Integer status = userInfoQuery.getStatus();

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();

        if(userInfoQuery==null){
             //用户没有填写筛选条件
            return  baseMapper.selectPage(pages,null);
        }

        wrapper.eq(StringUtils.isNotBlank(mobile),"mobile",mobile)
                .eq(status!=null,"status",status)
                .eq(userType!=null,"user_type",userType);


        return  baseMapper.selectPage(pages,wrapper);

    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);

        baseMapper.updateById(userInfo);
    }
}
